package com.learn.training.multithread.chapter6.minchapter6.demo1;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Counter {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private int[] counts=new int[5];

    public void increment(int index){
        writeLock.lock();//加写锁
        try {
            counts[index] += 1;
            System.out.println(Thread.currentThread().getName() + "  increment index " + index + "   " + Arrays.toString(counts));
        }finally {
            writeLock.unlock();//释放写锁
        }
    }

    public int[] get(){
        readLock.lock();//加读锁
        try {
            System.out.println(Thread.currentThread().getName() + "  get " + Arrays.toString(counts));
            return Arrays.copyOf(counts, counts.length);
        }finally {
            readLock.unlock();//释放读锁
        }
    }
}
